package com.chuangsi.project.admin.controller;

import com.chuangsi.project.admin.service.IPayOrderService;
import com.chuangsi.project.wechat.PayUtil;
import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "微信回调控制器")
@RestController
@RequestMapping("/wechat/callback")
@Slf4j
public class WechatCallbackController {
    @Autowired
    private IPayOrderService payOrderService;

    @ApiOperation(value = "微信支付回调", notes = "ywb")
    @PostMapping(value = "payment")
    public Map<String, String> payment(HttpServletRequest request) {
        log.info("微信支付回调----->进入回调");
        Map<String, String> map = new HashMap<>(2);
        String signature     = request.getHeader("Wechatpay-Signature");//应答的微信支付签名
        String serial        = request.getHeader("Wechatpay-Serial");//微信支付平台证书的序列号，验签必须使用序列号对应的微信支付平台证书
        String nonce         = request.getHeader("Wechatpay-Nonce");//签名中的随机数
        String timestamp     = request.getHeader("Wechatpay-Timestamp");//签名中的时间戳
        String signatureType = request.getHeader("Wechatpay-Signature-Type");//签名类型
        String requestBody = "";
        try {
            //读取请求体的信息
            ServletInputStream inputStream = request.getInputStream();
            StringBuffer stringBuffer = new StringBuffer();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String s;
            //读取回调请求体
            while ((s = bufferedReader.readLine()) != null) {
                stringBuffer.append(s);
            }
            requestBody = stringBuffer.toString();
        }catch (Exception e){
            e.printStackTrace();
            map.put("code","FAIL");
            map.put("message","失败");
            return map;
        }
//        signature = "T2mkslY4iEyreFIP9NIMXzK11yeTBSMEvwctlA9noMjTJ7fB4KRymuqJwFkWkg3l/owzWEQZyQ8UtVnjmH31VCziT5p231vCMGteWBO48MDcEUKN4Khgcu6+2iTFFLXnhwtB+J7Bgv1soqXPCGK0+BH6Tuk8UIqVDaikXpET26fQnybVb650VirPOG5NDRsXp+w4XtEC9lAsetbXYNpmimlxSQK/7ZATUuGFkLxyj9Em6haFiJWqQ+iGcV6+Rf14Y3S96mN3Hyd02/939Vv/eJmB4o7CjLw9gZ0IEBwF2UFCA6vMHv2ThrS4Cn8S3PHTKpaFUIZyFHnCNkIplISHsQ==";
//        serial = "PUB_KEY_ID_0117095758412025030600389500002170";
//        nonce = "wZv94H9Gq9RboBLrFnRcvQ1EloUV5GR4";
//        timestamp = "1742741499";
//        signatureType = "WECHATPAY2-SHA256-RSA2048";
//        requestBody = "{\"id\":\"40520e2c-b354-58f6-90e0-313e971799e6\",\"create_time\":\"2025-03-23T22:51:39+08:00\",\"resource_type\":\"encrypt-resource\",\"event_type\":\"TRANSACTION.SUCCESS\",\"summary\":\"支付成功\",\"resource\":{\"original_type\":\"transaction\",\"algorithm\":\"AEAD_AES_256_GCM\",\"ciphertext\":\"KtvVkqAD8+nLU/eRcEUUcWlFXeVG4e4LvbZeQ6puK+c+pW0/PlyiC0NWLcHQ8WaVoFHauFFKInQyVorfe+/BOs0G0utm/euQ8XdDt7FtmDk95n23kmF3XXWdffqaOoTUYXkHyJeVwbJUMr6p6GB+uPnaqsHCjyM56NvsjLH+Q8bj7XJEGuL6ORc21iHhf6dijemAspZzsqbOZiHciTJLZVTVioiy54Sfh0SBT4BqIhY7FVx/SQCRIAXVgwmO1cQm6iV0wPZceqORFLS02rHj2TIhSNSy4vpMDVPciCE+yU1Sxo7Ceuk/enOslZFg2SRKuot4TNAIJVZbnc/5EfDbAFT4PFNE4fx2SAAjc3t4Tqu/vaDZsln8Mmhu9nE9LmYBFtepIlhJakz/xqQTDgt4unR5n5se0LbbNkmDE1ROXki1YZp0ylQxBRsL/blzIZefkmgoh0we9YAhi1ci67oZBNCrtXX0gm9I6nQpbSY5WXJ2TpMwkVAwaM5WA6wlGi4Sblz64I1FjS/eJCkIXFJIAziANftyxPP0L9iTndnEyTeN9YbLS0KKtV96HaM1H3SBrfjTRV9IOM5iW29cV6aMxOcpg1j8d/8=\",\"associated_data\":\"transaction\",\"nonce\":\"nWn7R80BDj4B\"}}";
        log.info("微信支付回调支付签名:{}",signature);
        log.info("微信支付回调证书序列:{}",serial);
        log.info("微信支付回调的随机数:{}",nonce);
        log.info("微信支付回调的时间戳:{}",timestamp);
        log.info("微信支付回调签名类型:{}",signatureType);
        log.info("微信支付回调的返回体:{}",requestBody);
        // 构造 equestParam
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(serial)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .signType(signatureType)
                .body(requestBody)
                .build();
        // 初始化 NotificationParser   根据序列号
        NotificationParser parser = new NotificationParser(PayUtil.getNotificationConfig(serial));
        try {
            // 以支付通知回调为例，验签、解密并转换成 Transaction
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            String outTradeNo = transaction.getOutTradeNo();
            if(transaction.getTradeState().toString().equals("SUCCESS")){
                payOrderService.updateOrderstatus(outTradeNo,2);
            }
            map.put("code","SUCCESS");
            map.put("message","成功");
            log.info("支付通知回调：{}", transaction);
        } catch (ValidationException e) {
            e.printStackTrace();
            map.put("code","FAIL");
            map.put("message","失败");
            return map;
        }
        map.put("code","FAIL");
        map.put("message","失败");
        return map;
    }


}
